Skip to content

Service via decorator manager - #899

Merged
craigbarratt merged 5 commits into
custom-components:masterfrom
dmamelin:service-via-decorator-manager
Nov 24, 2026
Merged

craigbarratt merged 5 commits into
custom-components:masterfrom
dmamelin:service-via-decorator-manager

Conversation

@dmamelin

@dmamelin dmamelin commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Route @service through the decorator manager

Follow-up to #870.

Until now, @service ran the function itself, bypassing the decorator manager. Now a service call goes through the manager as an explicit call, so it shares the call pipeline with triggers.

Changes

  • @service goes through the decorator manager. A service call starts the call directly (FunctionDecoratorManager.start_call()), without the trigger handlers: @state_active and @time_active don't apply, as before, while call handlers (@task_unique) now do.
  • Shared request/response handling. RequestResponseDecorator (decorators/base.py) answers a request with the outcome of the call it starts. @service and @webhook_handler are built on it.
  • Service data is validated. The service is registered with a schema built from the function's signature, so Home Assistant rejects an undeclared field or a missing parameter without a default value before the function runs, like other integrations' services. A function with **kwargs accepts any other field.
  • @webhook_handler no longer waits for the timeout when the call ends without a result: a call cancelled while running (e.g. by a newer @task_unique call) or before the function starts gets 503, and a call handler that raises gives 500, right away instead of 504 after the timeout.

Service description from the signature

When the docstring isn't a yaml description, the service fields shown in Developer Tools → Actions and in the automation editor are now generated from the function's signature:

  • each parameter that can be passed by name is a field: keyword-only parameters are included, positional-only ones aren't;
  • a parameter without a default value is marked required;
  • a bool, number or string constant default value is shown as the field's default; a computed one isn't, so it's never published;
  • a bool, int, float, str, list or dict annotation (also X | None, Optional[X], list[int]) gives the field a matching input (toggle, integer box, number box, text, YAML object).
    @service
    def set_brightness(entity_id: str, level: int = 50, transition: float | None = None, *, notify: bool = False):
        """Set the brightness of a light."""

gives a required text field entity_id, an integer box level with default 50, a number box transition and a toggle notify. The previous generation dates from before Home Assistant had selectors and a UI for service calls (2021): it only listed the parameters, each with an argument <name> description and no selector, so the UI editor doesn't show them at all and the service data has to be written in YAML.

Breaking changes (@service)

  1. An exception in the function fails the service call with a HomeAssistantError, which stops a calling automation or script unless continue_on_error is set. Previously it was only logged and the call succeeded.
  2. A field the function doesn't declare fails the call before the function runs. Previously a TypeError was logged and the call succeeded, and undeclared names from the trigger kwargs (value, var_name, payload, topic, …) were dropped silently and the function ran.
  3. A missing parameter without a default value fails the call before the function runs. Previously a TypeError was logged and the call succeeded.
  4. @task_unique applies to service calls. A service call can cancel a running trigger call and vice versa, and with kill_me=True the service call is skipped.

Other changes

  • Each service call shows up in the logbook, like triggers.
  • Actions inside the function get a context whose parent is the service call's context.
  • A function returning None gives {} when a response is requested. Previously Home Assistant raised an error.

@dmamelin

Copy link
Copy Markdown
Contributor Author

FYI: the PR removing the legacy decorator subsystem is ready. It depends on this one, so I'll open it once this is merged. Happy to make any changes needed here.

@craigbarratt a lot has piled up since 2.1.1. How about releasing 2.2.0 after this is merged, and removing the legacy subsystem in the next release? That way users still have legacy_decorators: true as a fallback for one more release.

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @dmamelin, the pipeline change is a nice cleanup. First, an apology: in #870 I said it was fine for @state_active, @time_active and @task_unique to apply to @service. I've been mulling it over since, and I can't see a good reason to gate an explicit service call with the two @*_active decorators. A caller asked for the call, and the docs' vacation manual-override example relies on services not being gated. Sorry for changing direction after you did the work.

Requested changes:

  1. Keep @task_unique on services, but skip @state_active/@time_active. They're the only TriggerHandlerDecorators, so a class flag on TriggerDecorator (e.g. gated_by_trigger_handlers = True, set to False in ServiceDecorator) checked in FunctionDecoratorManager.dispatch() would do it. Two related details:
    • TriggerHandlerDecorator.validate() should only count gated triggers, so @service @state_active with no other trigger is still an error.
    • Service calls then won't touch @time_active's hold-off state, so the hold_off_send_last note and its docs can go. The docs can keep saying @*_active don't affect services.
  2. A blocking caller can hang. If the call task is cancelled before it starts, or a call handler raises, the result future is never set. A done-callback on data.call_task that resolves the future if it isn't done would cover both cases.
  3. Breaking change 3: silently ignoring undeclared service data removes the feedback for a typo in a field name. I'd prefer to keep the error for services.
  4. Breaking change 4: agreed, failing the call is the right behavior. Please keep it.
  5. Please document kwargs= on @service, or reject it.

@dmamelin

dmamelin commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @craigbarratt for the review! Before I get to the other points, I'd like to settle what @service is, since the answer affects how they should be done.

  1. A trigger, like the others. Then it goes through the full decorator manager pipeline: @*_active, @task_unique and any call/result handlers added later. The docs should then describe @service with the trigger decorators, not under "Other Function Decorators".
  2. A separate entry point, like @pyscript_compile/@pyscript_executor. Then none of the pipeline applies, @task_unique included, which is how it worked before.

Skipping @*_active while keeping @task_unique is a mix of the two.

I don't see a reason to restrict @service on purpose. Going through the pipeline doesn't force anything on the user: @*_active only applies if the function has it, and a function that must stay callable regardless of state just doesn't use it. In exchange, the system stays simple and uniform: every trigger works the same way.

@webhook_handler and furure @sentence_trigger is the closest analogue: also an explicit request whose caller waits for a response, and it's already a trigger in the pipeline. The docs say a falsy @state_active or a @task_unique collision returns 503 there. Treating @service differently would make two request/response entry points behave differently.

@dmamelin

Copy link
Copy Markdown
Contributor Author

One more point in favour of keeping @service in the regular pipeline: handlers we may add later.
For example, a @user_active/@group_active that checks the Home Assistant user behind the call's context. I wanted something like it while tracking a relay with @state_trigger that got switched on through a chain of unrelated user actions. For services it would be the most natural use: limiting who can call a service. If services skipped trigger handlers, that wouldn't be possible.

@craigbarratt

craigbarratt commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Thanks @dmamelin, good points, and I agree that a uniform pipeline is appealing, which is why I was initially supportive. But I've been thinking about it more, and I still think @state_active/@time_active shouldn't gate @service:

  1. @*_active decides whether an automatic trigger should run the function ("when any trigger occurs..."). A service call isn't a trigger: the caller has already decided to run it.
  2. "Just don't use @*_active" doesn't help a function that is both a service and a trigger, which is supported and tested:
    @time_trigger("cron(0 7 * * *)")
    @state_active("input_boolean.vacation == 'off'")
    @service
    def open_blinds(): ...
    The 7am run should be skipped on vacation, but the dashboard button should still work. Gating would force users to split this into two functions.
  3. It's a silent regression: today, as documented, a service call always runs. With gating, existing calls outside the active conditions would quietly do nothing, which is hard to debug.
  4. HA does the same: automation.trigger skips the automation's conditions by default.
  5. @task_unique is different in kind: @*_active decides whether a run should start, while @task_unique controls how concurrent runs interact however they started. So keeping it isn't an arbitrary mix.
  6. A future @user_active still fits: put the flag on each handler ("applies to service calls") rather than on ServiceDecorator. @state_active/@time_active opt out, and a handler that limits who can call a service opts in.

@webhook_trigger is a trigger by name and design, while @service exposes a function to be called, so I'm fine with them differing.

dmamelin and others added 5 commits November 23, 2026 03:08
… the caller hanging

Add RequestResponseDecorator, a base for a decorator that answers a request with the
result of the call it starts. It resolves the request's future when the call returns,
raises, is skipped or cancelled, or fails before the function runs, and cancels the
call when the caller goes away.

@webhook_handler is built on it: a call that fails or is cancelled before the function
runs is answered with 500/503 right away instead of after the timeout. Like Home
Assistant's REST API, it doesn't cancel the function when the client disconnects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A service call starts the call directly (FunctionDecoratorManager.start_call), so trigger
handlers (@state_active, @time_active) don't apply to it, while call handlers
(@task_unique) do. ServiceDecorator is a RequestResponseDecorator:

- an exception raised by the function fails the service call with a HomeAssistantError
  (the exception is still logged);
- a call skipped or cancelled by @task_unique, or a function returning None, gives an
  empty response when one is requested, like Home Assistant scripts;
- cancelling the caller cancels the function;
- each call fires pyscript_running, like triggers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…A services

Home Assistant now checks the service data before the call: a field the function
doesn't declare, or a missing parameter without a default value, fails the call
(a function with **kwargs accepts any other field). trigger_type and context
aren't service data.

The generated description follows the same parameters: no positional-only,
trigger_type or context fields, keyword-only ones included, parameters without
a default value marked required, simple default values shown, and a selector
from a simple type annotation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dmamelin
dmamelin force-pushed the service-via-decorator-manager branch from 8255605 to 81ab7a4 Compare November 24, 2026 14:25
@dmamelin

Copy link
Copy Markdown
Contributor Author

@craigbarratt thanks for the review. I've addressed all the points, rebuilt the history into 5 commits on the current master and updated the description.

  1. Done, slightly differently: instead of a class flag on TriggerDecorator, @service is no longer a trigger. A service call is an explicit call that goes through FunctionDecoratorManager.start_call(), which skips the trigger handlers (@state_active, @time_active) and keeps the call handlers (@task_unique). This way decorators stay unaware of each other. validate() counts only real triggers, so @service + @state_active alone is an error. The hold-off changes and docs are gone.
  2. Done as you suggested: a done-callback on the call task answers the caller when the call ends without a result (cancelled before it starts, a call handler raised). The future handling is shared with @webhook_handler in RequestResponseDecorator, so @webhook_handler now returns 500/503 right away in these cases instead of after the timeout. When the caller is cancelled (e.g. a restarted automation), the function is cancelled and the caller waits for its cleanup, as with await task before.
  3. Done, a bit stricter: the service is registered with a schema built from the signature, so Home Assistant rejects an undeclared field, or a missing parameter without a default value, before the function runs, like other integrations' services. **kwargs accepts any field.
  4. Kept.
  5. Rejected: @service isn't a trigger anymore, so kwargs= is an invalid keyword argument.

Also, without a yaml docstring the service fields are now generated from the signature: required fields, constant default values (never computed ones), and a UI input from a simple type annotation. See the description for details.

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @dmamelin, this addresses everything, and making @service an explicit call through start_call() is cleaner than the flag I suggested. The shared RequestResponseDecorator is a nice bonus for @webhook_handler, and generating the fields and selectors from the signature is a real improvement for the UI.

I also checked a few cases outside the tests, and they all behave well:

  • a call with target: fills entity_id;
  • a non-blocking call whose function raises is just logged;
  • calling a pyscript service from pyscript with an undeclared field raises in the caller;
  • a required positional-only parameter fails the call with a clear HomeAssistantError.

I'll fix a small doc nit in a follow-up commit: "description that appears is in the Services tab of the Developer Tools page" has a stray "is", and the tab is now called Actions.

@craigbarratt
craigbarratt merged commit 9fe4ce2 into custom-components:master Nov 24, 2026
6 checks passed
This was referenced Nov 24, 2026
@dmamelin
dmamelin deleted the service-via-decorator-manager branch November 25, 2026 08:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants